package controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.CategoryModel;
import models.LinkModel;

import systems.ConfigSystem;
import entities.Category;
import entities.Link;
import entities.SiteConfig;
import forms.CaptchaForm;
import forms.LinkForm;

public class SubmitSiteServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		SiteConfig config = ConfigSystem.getConfigs();
		
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		List<Category> categories = categoryModel.getAll();
		
		Link link = new Link();
		
		request.setAttribute("link", link);
		request.setAttribute("categories", categories);
		request.setAttribute("check", check);
		request.setAttribute("form", "add");
		try {
			request.getRequestDispatcher("/templates/" + config.getTemplate() + "/pages/link-form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		SiteConfig config = ConfigSystem.getConfigs();
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		List<Category> categories = categoryModel.getAll();
		
		LinkModel linkModel = LinkModel.getInstance();
		Link link = new Link();
		
		TreeMap<String, Object> forms = LinkForm.checkValid(request, link);
		TreeMap<String, String> check = (TreeMap<String, String>) forms.get("checkValid");
		link = (Link) forms.get("link");
		
		check = CaptchaForm.checkValid(request, check);
		
		if (check.size() == 0) {
			link.setId(IdUniqueHelper.getId());
			link.setAuthKey(IdUniqueHelper.getId() + System.currentTimeMillis());
			
			linkModel.insert(link);
			
			request.setAttribute("success", "Add success link " + link.getId());
			
			link = new Link();
		}
		
		request.setAttribute("link", link);
		request.setAttribute("categories", categories);
		request.setAttribute("check", check);
		request.setAttribute("form", "add");
		try {
			request.getRequestDispatcher("/templates/" + config.getTemplate() + "/pages/link-form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
